/* eslint-disable react-hooks/exhaustive-deps */
import React, {useEffect, useState} from 'react';
import {Toast, Colors} from 'react-native-ui-lib';
import {DeviceEventEmitter} from 'react-native';
import {useColorScheme} from 'react-native';
import {connect, useDispatch} from 'react-redux';

let RootToast = () => {
  const isDarkMode = useColorScheme() === 'dark';
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch({
      type: 'CHANGE_THEME',
      appTheme: isDarkMode ? 'dark' : 'light',
    });
  }, [isDarkMode]);

  const [state, setstate] = useState({
    visible: false,
    //backgroundColor: Colors.primaryColor,
    onDismiss: () => {
      setstate(s => ({
        ...s,
        visible: false,
      }));
    },
    showDismiss: false,
    showLoader: false,
  });

  useEffect(() => {
    const listen = DeviceEventEmitter.addListener('toast', params => {
      setstate({
        ...state,
        visible: true,
        ...params,
      });
    });
    return () => {
      listen.remove();
    };
  }, []);

  return (
    <Toast
      visible={state.visible}
      position="top"
      icon={
        state.type === 'warning'
          ? require('@/assets/warning.png')
          : state.type === 'error'
          ? require('@/assets/error.png')
          : state.type === 'info'
          ? require('@/assets/info.png')
          : state.type === 'success'
          ? require('@/assets/success.png')
          : require('@/assets/logo_w.png')
      }
      backgroundColor={
        state.type === 'success' ? Colors.green30 : Colors.primaryColor
      }
      message={state.message}
      onDismiss={state.onDismiss}
      autoDismiss={1000}
      showDismiss={state.showDismiss}
      showLoader={state.showLoader}
    />
  );
};

export default RootToast;
